//
//  MoreEqViewController.m
//  TY_CarMachine
//
//  Created by dfwx on 2021/3/6.
//  Copyright © 2021 zhongDaoDianZi. All rights reserved.
//

#import "MoreEqViewController.h"
#import "UIScrollView+GestureConflict.h"
#import "MoreEqCell.h"
#import "BlueToothManager.h"
#import "ProjectManager.h"
#import "CalculateTool.h"
#import "CustomBlueListView.h"


@interface MoreEqViewController () <UITableViewDelegate, UITableViewDataSource, MoreEqCellDelegate, CustomBlueListViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *dataArray;
@property (nonatomic, strong) UIButton *rightButton;
@property (nonatomic, strong) CustomBlueListView *customBlueListView;

@end

@implementation MoreEqViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.barStyle = UIBarStyleBlack;

    self.title = NSLocalizedString(@"EQ", nil);
    [self setUpUI];
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(receiveDataHandle:) name:@"dataReceiveNotification" object:nil];
    // Do any additional setup after loading the view from its nib.
}

- (void)setUpUI {
    
    [self setUpleftBarButton];
//    self.nameArray = @[@"BAL",@"FAD",@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8",@"9",@"10",@"11",@"12",@"13",@"14"];
    
    [self.dataArray removeAllObjects];
    [self.dataArray addObjectsFromArray:self.dspEqValueArray];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:NSStringFromClass([MoreEqCell class]) bundle:nil] forCellReuseIdentifier:NSStringFromClass([MoreEqCell class])];
    
    
}

- (void)setUpRightButton {
    
    self.rightButton = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 21, 21)];
    [self.rightButton setBackgroundImage:[UIImage imageNamed:@"Reset"] forState:UIControlStateNormal];
    [self.rightButton addTarget:self action:@selector(rightButtonClickedHandle:) forControlEvents:UIControlEventTouchUpInside];
    [self.rightButton setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:self.rightButton];
}

- (void)receiveDataHandle:(NSNotification *)noti {
    
    NSLog(@"进入通知的%@",noti.object);
    NSString *data = noti.object;
    if (data.length >= 4) {
        NSString *four = [data subStringWithRangeForNil:NSMakeRange(0, 4)];
//        if ([four isEqualToString:@"0a03"]) {
//            NSString *value = [data substringWithRange:NSMakeRange(5, 1)];
//            [self.dataArray replaceObjectAtIndex:0 withObject:value];
////            [self.tableView reloadRowsAtIndexPaths:@[[NSIndexPath indexPathForRow:0 inSection:0]] withRowAnimation:UITableViewRowAnimationAutomatic];
//            MoreEqCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0]];
//            NSString *value1 = self.dataArray[0];
//            NSInteger intValue = [CalculateTool tempSingleHexToSingleDecimal:value1];
//            cell.slder.value = intValue;
//            cell.valueLabel.text = [NSString stringWithFormat:@"%ld",intValue-7];
//        }else if ([four isEqualToString:@"0a04"]) {
//            NSString *value = [data substringWithRange:NSMakeRange(5, 1)];
//            [self.dataArray replaceObjectAtIndex:1 withObject:value];
//            MoreEqCell *cell = [self.tableView cellForRowAtIndexPath:[NSIndexPath indexPathForRow:1 inSection:0]];
//            NSString *value1 = self.dataArray[1];
//            NSInteger intValue = [CalculateTool tempSingleHexToSingleDecimal:value1];
//            cell.slder.value = intValue;
//            cell.valueLabel.text = [NSString stringWithFormat:@"%ld",intValue-7];
//
        //        }else
        if ([four isEqualToString:@"0a05"]) {
            
            NSString *number = [data subStringWithRangeForNil:NSMakeRange(5, 1)];
            NSString *value = [data subStringWithRangeForNil:NSMakeRange(7, 1)];
            NSInteger numberValue = [CalculateTool tempSingleHexToSingleDecimal:number];
            [self.dataArray replaceObjectAtIndex:numberValue withObject:value];
            [self.tableView reloadData];
            
        }else if ([four isEqualToString:@"0a06"]) {
            
            for (NSInteger i = 0; i < 14; i ++) {
                //                NSString *number = [data substringWithRange:NSMakeRange(5, 1)];
                //                NSString *value = [data substringWithRange:NSMakeRange(7, 1)];
                //                NSInteger numberValue = [CalculateTool tempSingleHexToSingleDecimal:number];
                [self.dataArray replaceObjectAtIndex:i withObject:@"7"];
            }
            
            [self.tableView reloadData];
            
        }
        
        [BlueToothManager shareInstance].eqDataArray = self.dataArray;
        
    }
}

- (void)setUpleftBarButton {
    UIButton *left = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 20)];
    [left setBackgroundImage:[UIImage imageNamed:@"eqReturn"] forState:UIControlStateNormal];
    [left setTitleColor:[UIColor redColor] forState:UIControlStateNormal];
    [left addTarget:self action:@selector(leftBarButtonClicked:) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:left];
    
    [self setUpRightButton];
    
}

- (void)rightButtonClickedHandle:(UIButton *)sender {
    
//    for (NSInteger i = 0; i <14; i++) {
//
//
//        NSString *numberHex = [CalculateTool hexValueToHesxString:i];
//            NSString *hexValue = [CalculateTool hexValueToHesxString:7];
//            NSString *command = [NSString stringWithFormat:@"0a05%@%@",numberHex,hexValue];
//            [self sendDataWithData:command];
//
//    }
    
    
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:NSLocalizedString(@"WARM_TIPS", nil) message:NSLocalizedString(@"reset", nil) preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"cancle", nil) style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
    }];
    UIAlertAction *sureAction = [UIAlertAction actionWithTitle:NSLocalizedString(@"sure", nil) style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [self sendDataWithData:@"0a06"];

    }];
    [alertVC addAction:cancleAction];
    [alertVC addAction:sureAction];
    [self presentViewController:alertVC animated:YES completion:nil];
    
}

- (void)leftBarButtonClicked:(UIButton *)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
//    [self.navigationController popViewControllerAnimated:YES];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    return self.nameArray.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    return 60;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    MoreEqCell *cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([MoreEqCell class]) forIndexPath:indexPath];
    cell.nameLabel.text = self.nameArray[indexPath.row];
    cell.tag = indexPath.row;
    cell.delegate = self;
    NSString *value = self.dataArray[indexPath.row];
    NSInteger intValue = [CalculateTool tempSingleHexToSingleDecimal:value];
    cell.slder.value = intValue;
    cell.valueLabel.text = [NSString stringWithFormat:@"%d",intValue-7];
    return cell;
}

- (void)MoreEqCellValueChangeWithTag:(NSInteger)tag withValue:(NSInteger)value {
    
//    if (tag == 0) {
//        NSString *hexValue = [CalculateTool hexValueToHesxString:value];
//
//        NSString *command = [NSString stringWithFormat:@"0a03%@",hexValue];
//        [self sendDataWithData:command];
//    }else if (tag == 1) {
//        NSString *hexValue = [CalculateTool hexValueToHesxString:value];
//
//        NSString *command = [NSString stringWithFormat:@"0a04%@",hexValue];
//        [self sendDataWithData:command];
//    }else {
        
        NSString *numberHex = [CalculateTool hexValueToHesxString:tag];
        NSString *hexValue = [CalculateTool hexValueToHesxString:value];
        NSString *command = [NSString stringWithFormat:@"0a05%@%@",numberHex,hexValue];
        [self sendDataWithData:command];
        
//    }
    
}

-(void)sendDataWithData:(NSString *)data{
    NSLog(@"发出data:%@",data);
    if ([BlueToothManager shareInstance].peripheral != nil && [BlueToothManager shareInstance].peripheral.state == CBPeripheralStateConnected) {
        [[BlueToothManager shareInstance].peripheral writeValue:[CalculateTool convertHexStrToMutableData:data] forCharacteristic:[BlueToothManager shareInstance].characteristic type:CBCharacteristicWriteWithResponse];
    }else{
        [NSTimer scheduledTimerWithTimeInterval:2 repeats:NO block:^(NSTimer * _Nonnull timer) {
            if ([BlueToothManager shareInstance].peripheral == nil || [BlueToothManager shareInstance].peripheral.state != CBPeripheralStateConnected){
//                [[BlueToothManager shareInstance] showBlueListView:self.view];
            }
        }];
    }
}

- (NSMutableArray *)dataArray {
    
    if (!_dataArray) {
        _dataArray = [NSMutableArray array];
    }
    return _dataArray;
}


-(CustomBlueListView *)customBlueListView{
    if (!_customBlueListView) {
        _customBlueListView = [[[NSBundle mainBundle]loadNibNamed:@"CustomBlueListView" owner:nil options:nil]lastObject];
        _customBlueListView.frame = self.view.frame;
        _customBlueListView.center = self.view.center;
        _customBlueListView.delegate = self;
        _customBlueListView.tableView.delegate = self;
        _customBlueListView.tableView.dataSource = self;
    }
    return _customBlueListView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
